package eoeProject.edenOfEast.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnector {

	private  static DBConnector Instance = new DBConnector();
	public static DBConnector getInstance(){
		return Instance;
	}
	private Statement stmt;
	private Connection con;
	private ResultSet rs;

	private  DBConnector() {
		    try {

		    	 // ドライバクラスをロード
		    	Class.forName("com.mysql.jdbc.Driver");

		    	// データベースへ接続
		    	con = DriverManager.getConnection(EOEProperties.getInstance().getProperty("db.connection"),EOEProperties.getInstance().getProperty("db.user"),EOEProperties.getInstance().getProperty("db.password"));

		    	stmt = con.createStatement();

		    }catch (SQLException e1) {
			      System.out.println(
					        "SQLException: " + e1.getMessage());
					      System.out.println(
					        "    SQLState: " + e1.getSQLState());
					      System.out.println(
					        " VendorError: " + e1.getErrorCode());
					    }catch (Exception e2) {
					      System.out.println(
					        "Exception: " + e2.getMessage());
					    }
		  }

		  public ResultSet get(String sql){
		   try {
		      //結果セットを格納するオブジェクト
			   rs = stmt.executeQuery(sql);


		      return rs;
		    }catch (SQLException e1) {
		      System.out.println(
		        "SQLException: " + e1.getMessage());
		      System.out.println(
		        "    SQLState: " + e1.getSQLState());
		      System.out.println(
		        " VendorError: " + e1.getErrorCode());
		      return null;
		    }catch (Exception e2) {
		      System.out.println(
		        "DBException: " + e2.getMessage());
		      return null;
		    }

		  }

		  public Boolean set(String sql){
			   try {
			      //結果セットを格納するオブジェクト
				   stmt.executeUpdate(sql);


			      return true;
			    }catch (SQLException e1) {
			      System.out.println(
			        "SQLException: " + e1.getMessage());
			      System.out.println(
			        "    SQLState: " + e1.getSQLState());
			      System.out.println(
			        " VendorError: " + e1.getErrorCode());
			      return true;
			    }catch (Exception e2) {
			      System.out.println(
			        "DBException: " + e2.getMessage());
			      return false;
			    }

		  }

		  public void closeDB(){
		      //データベースの切断
		      try {
		    	  rs.close();
		    	  stmt.close();
		    	  con.close();

			} catch (SQLException e) {
				System.out.println(
				        "DBException: " + e.getMessage());
			}

		  }

}
